/*
 *  Copyright (c) 2011 Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU Lesser Public License v2.1
 *  which accompanies this distribution, and is available at
 *  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 *  Contributors:
 *      Leibniz Institute of Plant Genetics and Crop Plant Research (IPK), Gatersleben, Germany - RMI Client, FileChooser and WebDAV
 */
package de.ipk_gatersleben.bit.bi.edal.webdav.sample;
import java.io.IOException;
import java.util.Properties;

import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.ssl.SslSocketConnector;

import de.ipk_gatersleben.bit.bi.edal.primary_data.EdalConfiguration;
import de.ipk_gatersleben.bit.bi.edal.rmi.client.ClientDataManager;
import de.ipk_gatersleben.bit.bi.edal.webdav.wrapper.FileSystemCache;

public class WebdavServer {
	private Server server;
	private static int EDAL_PORT = 0;
	private static String EDAL_HOST = "";
	private static int WEBDAV_SSLPORT = 8443;
	
	public WebdavServer() {
		final Properties prop = new Properties();

		/* load default webDAV-Properties */
		try {
			prop.load(Main.class.getResourceAsStream("/eDALwebDAV.properties"));
			EDAL_HOST = prop.getProperty("server.host");
			EDAL_PORT = Integer.parseInt(prop.getProperty("server.port"));
			WEBDAV_SSLPORT = Integer.parseInt(prop
					.getProperty("browser.sslport"));
		} catch (final IOException e) {
			ClientDataManager.logger.fatal(
					"error loading default WebDAV properties", e);
			System.exit(-1);
		}
		server = new Server(WEBDAV_SSLPORT);
		SslContextFactory sslContextFactory = new SslContextFactory();

		sslContextFactory.setKeyStorePassword(EdalConfiguration.KEYSTORE_PASSWORD);
		sslContextFactory.setKeyStore(EdalConfiguration.KEY_STORE_PATH.toString());

		SslSocketConnector sslConnector = new SslSocketConnector(
				sslContextFactory);
		sslConnector.setPort(WEBDAV_SSLPORT);
		server.setConnectors(new Connector[] { sslConnector });
		
		ContextHandlerCollection contexts = new ContextHandlerCollection();
		
		contexts.setHandlers(new Handler[] 
			{ new AppContextBuilder().buildWebAppContext()});
		
		server.setHandler(contexts);
	}
	
	
	public void start() throws Exception {		
		FileSystemCache.init();
		server.start();
	}
	
	public void stop() throws Exception {
		server.stop();
		server.join();
	}
	
	public boolean isStarted() {
		return server.isStarted();
	}
	
	public boolean isStopped() {
		return server.isStopped();
	}
}
